import { getArticleDetailByIdAPI } from 'api/content'
import React, { Component } from 'react'
import {
  Card,
  Breadcrumb,
  Form,
  Input,
  Button,
  Radio,
  Upload,
  Modal,
  Space,
  message,
} from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { Link } from 'react-router-dom'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import style from './index.module.scss'
import ArtChannel from 'components/ArtChannel'
import { baseURL } from 'utils/request'
import { pubArticleIdAPI, editArticleIdAPI } from 'api/content'

export default class Public extends Component {
  state = {
    fileList: [],
    previewVisible: false,
    previewImage: '',
    previewTitle: '',
    fileList: [],
    type: 1,
    initialValues: { type: 1, content: '' },
    draft: false,
  }
  componentDidMount() {
    this.isHasQuery()
  }

  // 判断当前路由带不带参数 带参数就是内容管理调过来的 不戴就是点击发布文章调过来的
  isHasQuery = async () => {
    const { id } = this.props.match.params
    this.id = id
    if (id) {
      const {
        data: {
          title,
          channel_id,
          content,
          cover: { images, type },
        },
      } = await getArticleDetailByIdAPI(id)

      this.form.setFieldsValue({ title, channel_id, content, type })
      const fileList = images.map((item) => {
        return { url: item }
      })
      this.setState({ fileList, type })
    } else {
      this.form.setFieldsValue({ type: 1, content: '' })
    }
  }
  // 上传图片前的校验
  beforeUpload = (file) => {
    if (file.size / 1024 > 200) {
      message.warning('请上传200kb以内的图片')
      return Upload.LIST_IGNORE
    } else if (!['image/jpeg', 'image/png'].includes(file.type)) {
      message.warning('请上传jpg,png类型的照片')
      return Upload.LIST_IGNORE
    }
    return true
  }
  // base64
  getBase64(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => resolve(reader.result)
      reader.onerror = (error) => reject(error)
    })
  }
  // 预览图片
  handlePreview = async (file) => {
    if (!file.url && !file.preview) {
      file.preview = await this.getBase64(file.originFileObj)
    }

    this.setState({
      previewImage: file.url || file.response.data.url || file.preview,
      previewVisible: true,
    })
  }
  // 选中图片
  handleChange = ({ fileList }) => this.setState({ fileList })
  // 取消选中
  handleCancel = () => this.setState({ previewVisible: false })

  // 切换图片数量
  typeChange = (e) => {
    this.setState({ type: e.target.value })
  }

  // 发布文章
  onFinish = async ({ title, channel_id, type, content }) => {
    const { fileList, draft } = this.state
    // 拿到标准的图片
    let images = []
    if (fileList.length) {
      images = fileList.map((item) => item.url || item.response.data.url)
    }
    if (type !== fileList.length) {
      return message.error('请选择正确数量的图片')
    }
    try {
      const data = {
        title,
        channel_id,
        cover: { type, images },
        content,
      }
      if (!this.id) {
        // 发布 存入草稿
        await pubArticleIdAPI(data, { draft })
        !draft
          ? message.success('文章发布成功')
          : message.success('存入草稿成功')
      } else {
        await editArticleIdAPI(this.id, { draft }, data)
        !draft
          ? message.success('文章修改成功')
          : message.success('存入草稿成功')
      }
      this.props.history.push('/home/articleList')
    } catch (error) {
      message.error('服务器异常')
    }
  }
  // 存入草稿
  addDraft = () => {
    this.setState({ draft: true }, this.form.submit())
  }
  render() {
    const { fileList, previewVisible, previewImage, type, initialValues } =
      this.state

    return (
      <div className={style.publish}>
        <Card
          title={
            <Breadcrumb>
              <Breadcrumb.Item>
                <Link to="/home">首页</Link>
              </Breadcrumb.Item>
              <Breadcrumb.Item>文章管理</Breadcrumb.Item>
            </Breadcrumb>
          }
        >
          <Form
            ref={(form) => (this.form = form)}
            name="basic"
            labelCol={{ span: 4 }}
            onFinish={this.onFinish}
            initialValues={initialValues}
          >
            <Form.Item
              label="标题"
              name="title"
              wrapperCol={{ span: 6 }}
              rules={[
                {
                  required: true,
                  message: '请输入标题',
                },
              ]}
            >
              <Input placeholder="请输入文章标题" />
            </Form.Item>

            <Form.Item
              label="频道"
              name="channel_id"
              wrapperCol={{ span: 6 }}
              rules={[
                {
                  required: true,
                  message: '请勾选频道',
                },
              ]}
            >
              <ArtChannel></ArtChannel>
            </Form.Item>

            <Form.Item label="封面" name="type">
              <Radio.Group onChange={this.typeChange}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
                {/* <Radio value={-1}>自动</Radio> */}
              </Radio.Group>
            </Form.Item>
            {type !== 0 && (
              <Form.Item wrapperCol={{ offset: 4 }} name="images">
                <Upload
                  action={`${baseURL}/upload`}
                  listType="picture-card"
                  fileList={fileList}
                  name="image"
                  onPreview={this.handlePreview}
                  onChange={this.handleChange}
                  beforeUpload={this.beforeUpload}
                >
                  {fileList.length < type && (
                    <div>
                      <PlusOutlined />
                      <div style={{ marginTop: 8 }}>Upload</div>
                    </div>
                  )}
                </Upload>
              </Form.Item>
            )}
            <Form.Item
              label="内容"
              name="content"
              rules={[
                {
                  required: true,
                  message: '请输入内容',
                },
              ]}
            >
              <ReactQuill
                theme="snow"
                placeholder="请输入文章内容..."
                rules={[{ required: true, message: '请输入文章内容' }]}
              ></ReactQuill>
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 4 }}>
              <Space>
                <Button type="primary" size="large" htmlType="submit">
                  {this.id ? '修改文章' : '发布文章'}
                </Button>
                <Button size="large" onClick={this.addDraft}>
                  存入草稿
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Card>
        {/* 图片预览 */}
        <Modal
          visible={previewVisible}
          title={'预览图片'}
          footer={null}
          onCancel={this.handleCancel}
        >
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </div>
    )
  }
}
